using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Globalization;

using Pampa.Common.Utils;

namespace Pampa.WebControls
{
    [ToolboxData("<{0}:DatePicker runat=server></{0}:DatePicker>")]
    [DesignerAttribute(typeof(BaseDesigner), typeof(System.ComponentModel.Design.IDesigner))]
    public class DatePicker : BaseControl
    {
        DatePickerType type;
        DateTime? date;
        string onClientChange;

        string[] dayNames;
        string[] monthNames;

        public DatePicker()
        {
            this.Type = DatePickerType.FullDate;
            this.CssClass = "datePickerDefault";
            this.clientClass = "DatePicker";

            dayNames = CultureInfo.CurrentCulture.DateTimeFormat.AbbreviatedDayNames;
            monthNames = CultureInfo.CurrentCulture.DateTimeFormat.MonthNames;
        }

        #region Properties

        public DatePickerType Type
        {
            get { return type; }
            set { type = value; }
        }

        public DateTime? Date
        {
            get { return date; }
            set { date = value; }
        }

        public string OnClientChange
        {
            get { return onClientChange; }
            set { onClientChange = value; }
        }

        private string ObjectName
        {
            get
            {
                return "dp" + this.ID.Replace(".", "_");
            }
        }

        #endregion

        #region Load

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.CssClass == "datePickerDefault")
                RegisterStyleSheet("Pampa.WebControls/DatePicker.css");

            RegisterLibrary("Pampa.Common/Common.js");
            RegisterLibrary("Pampa.WebControls/FocusManager.js");
            RegisterLibrary("Pampa.WebControls/Calendar.js");
            RegisterLibrary("Pampa.WebControls/MonthCalendar.js");
            RegisterLibrary("Pampa.WebControls/DatePicker.js");
            RegisterLibrary("Pampa.WebControls/Selector.js");

            // recupero el valor tomado en el Customer
            if (Page.IsPostBack)
            {
                LoadValue();
            }
        }

        #endregion

        #region Render

        protected override void Render(HtmlTextWriter writer)
        {
            writer.AddAttribute("id", "cont_" + this.ID);
            writer.AddAttribute("class", this.CssClass);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderEndTag();

            RenderDefinitions(writer);
        }

        /// <summary>
        /// Construyo el objeto Customer que representa al combo
        /// </summary>
        private void RenderDefinitions(HtmlTextWriter output)
        {
            output.WriteLine("<script type=\"text/javascript\">");
            output.WriteLine("var " + this.ObjectName + " = new " + this.clientClass + "(\"" + this.ID + "\");");

            // Properties                
            RenderProperties(output);

            output.WriteLine(this.ObjectName + ".show(\"cont_" + this.ID + "\");");
            output.WriteLine("</script>");
        }

        protected virtual void RenderProperties(HtmlTextWriter output)
        {
            string objectName = this.ObjectName;

            output.WriteLine(objectName + ".dateFormat = \"" + Formats.DateFormat + "\";");
            output.WriteLine(objectName + ".cssClass = \"" + this.CssClass + "\";");
            output.WriteLine(objectName + ".enabled = " + this.Enabled.ToString().ToLower() + ";");
            output.WriteLine(objectName + ".calendarID = \"calendar_" + this.ID + "\";");
            output.WriteLine(objectName + ".onChange = \"" + this.onClientChange + "\";");
            output.WriteLine(objectName + ".type = \"" + Enum.GetName(typeof(DatePickerType), this.Type) + "\";");

            if (this.Type == DatePickerType.FullDate)
                output.WriteLine(objectName + ".calendar = new Calendar(\"calendar_" + this.ID + "\")");
            else
                output.WriteLine(objectName + ".calendar = new MonthCalendar(\"calendar_" + this.ID + "\")");

            RenderCalendarProperties(output);

            // Seteo la fecha del calendar
            if (this.Date.HasValue)
            {
                output.WriteLine(objectName + ".calendar.validDate = true;");

                if (this.Type == DatePickerType.FullDate)
                    output.WriteLine(objectName + ".setValue(\"" + this.Date.Value.ToShortDateString() + "\");");
                else
                    output.WriteLine(objectName + ".setValue(\"" + this.Date.Value.ToString("MM/yyyy") + "\");");
            }
            else
            {
                output.WriteLine(objectName + ".calendar.validDate = false;");
                output.WriteLine(objectName + ".calendar.year = " + DateTime.Now.Year + ";");
                output.WriteLine(objectName + ".calendar.month = " + DateTime.Now.Month + ";");
            }
        }

        protected virtual void RenderCalendarProperties(HtmlTextWriter output)
        {
            string objectName = this.ObjectName;

            if (this.Type == DatePickerType.FullDate)
            {
                for (int i = 0; i < 12; i++)
                {
                    output.WriteLine(objectName + ".calendar.monthNames[" + i.ToString() + "] = \"" + monthNames[i] + "\";");
                }

                for (int i = 0; i < 7; i++)
                {
                    output.WriteLine(objectName + ".calendar.dayNames[" + i.ToString() + "] = \"" + dayNames[i] + "\";");
                }
            }
            else
            {
                for (int i = 0; i < 12; i++)
                {
                    output.WriteLine(objectName + ".calendar.monthNames[" + i.ToString() + "] = \"" + monthNames[i].Substring(0, 3).ToUpper() + "\";");
                }
            }
            
            output.WriteLine(objectName + ".calendar.cssClass = \"calendar\";");
            output.WriteLine(objectName + ".calendar.focuseable = true;");
            output.WriteLine(objectName + ".calendar.parentID = \"" + this.ID + "\";");
            output.WriteLine(objectName + ".calendar.titleFormat = 1;");
        }

        #endregion

        #region Recover Client Data

        private void LoadValue()
        {
            if (!(String.IsNullOrEmpty(Page.Request[this.ID])))
            {
                if (this.Type == DatePickerType.FullDate)
                {
                    DateTime dateTime;
                    if (DateTime.TryParse(Page.Request[this.ID], out dateTime))
                        this.Date = dateTime;
                }
                else
                { 
                    int barPos = Page.Request[this.ID].IndexOf("/");
                    int month = int.Parse(Page.Request[this.ID].Substring(0, barPos));
                    int year = int.Parse(Page.Request[this.ID].Substring(barPos+1, Page.Request[this.ID].Length - barPos -1));

                    this.Date = new DateTime(year, month, 1);
                }
            }
        }

        #endregion
    }
}
